package com.beta;

import com.alibaba.fastjson.JSON;
import org.junit.runner.RunWith;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

/*
 * @TransactionConfiguration(transactionManager="transactionManager",defaultRollback=true)
 * transactionManager的默认取值是"transactionManager"，
 * defaultRollback的默认取值是true，当然，你也可以改成false。
 * true表示测试不会对数据库造成污染,false的话当然就会改动到数据库中了。
 * 在方法名上添加@Rollback(false)表示这个测试用例不需要回滚。
 */
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:/server/spring-core.xml"})
@Transactional
@Rollback
//@TransactionConfiguration(transactionManager = "transactionManager", defaultRollback = true)
@ActiveProfiles(value = "develop")
public abstract class SpringTxTestCase extends AbstractJUnit4SpringContextTests {

//    @Before
//    public void init(){
//        Environment env = applicationContext.getEnvironment();
//        String profile = env.getActiveProfiles()[0];
//        System.setProperty("spring.profiles.active", profile);
//    }

    public void printObject(Object object) {
        if (object instanceof Date) {
            printDate((Date) object);
        } else if (object instanceof LocalDateTime) {
            printLocalDateTime((LocalDateTime) object);
        } else {
            System.err.println(JSON.toJSONString(object));
        }
    }

    public void printDate(Date date) {
        printLocalDateTime(date.toInstant().atZone(ZoneId.systemDefault()).toLocalDateTime());
    }

    public void printLocalDateTime(LocalDateTime localDateTime) {
        System.err.println(localDateTime.format(DateTimeFormatter.ISO_DATE_TIME));
    }

}
